/**
 * Copyright &copy; 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package com.thinkgem.jeesite.modules.front.web.pay.ali;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.thinkgem.jeesite.common.utils.CacheUtils;
import com.thinkgem.jeesite.common.web.BaseController;
import com.thinkgem.jeesite.modules.accountinfo.entity.AccountInfo;
import com.thinkgem.jeesite.modules.config.entity.ali.ConfigAlipay;
import com.thinkgem.jeesite.modules.config.service.ali.ConfigAlipayService;
import com.thinkgem.jeesite.modules.front.entity.cart.GenCart;
import com.thinkgem.jeesite.modules.front.service.cart.GenCartService;
import com.thinkgem.jeesite.modules.pay.entity.log.EcPayLog;
import com.thinkgem.jeesite.modules.pay.service.log.EcPayLogService;
import com.thinkgem.jeesite.modules.shop.entity.info.ShopOrderInfo;
import com.thinkgem.jeesite.modules.shop.entity.order.ShopOrder;
import com.thinkgem.jeesite.modules.shop.service.order.ShopOrderService;


/**
 * 支付Controller（支付宝）
 * 
 * @author Egan
 * @version 2016-02-15
 */
@Controller
@RequestMapping(value = "${frontPath}/pay/ali")
public class ALIPayController extends BaseController {
	private static Log log = LogFactory.getLog(ALIPayController.class);
	
	@Autowired EcPayLogService ecPayLogService;
	
	@Autowired ShopOrderService shopOrderService;
	
	@Autowired ALIPayService aliPayService;
	
	@Autowired ConfigAlipayService configAlipayService;
	
	@Autowired
	GenCartService genCartService;
	
	@RequestMapping(value = "forPay")
	public String forPay(HttpServletRequest req, HttpServletResponse resp,Model model) {
		try {
			
			//商户订单号，商户网站订单系统中唯一订单号，必填
			String coNum = new String(req.getParameter("coNum").getBytes("ISO-8859-1"),"UTF-8");
			 //付款金额，必填
	        String txnAmt = new String(req.getParameter("txnAmt").getBytes("ISO-8859-1"),"UTF-8");
	        ConfigAlipay configAlipay = configAlipayService.getConfigAlipay();
	        
	        ShopOrder order = shopOrderService.findByCoNum(coNum);
			List<ShopOrderInfo> infos = order.getShopOrderInfoList();
			StringBuilder sbBody = new StringBuilder();
			for (ShopOrderInfo info : infos) {
				sbBody.append(info.getName()).append(",");
			}
	        model.addAttribute("coNum",coNum);
	        model.addAttribute("txnAmt",txnAmt);
	        model.addAttribute("body",sbBody.toString().substring(0, sbBody.toString().length() - 1));
	        model.addAttribute("subject",sbBody.toString().substring(0, sbBody.toString().length() - 1));
	        model.addAttribute("configAlipay",configAlipay);
	        
	        
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "modules/pay/ali/alipayapi";
	}
	
	@RequestMapping(value = "forMobilePay")
	public String forMobilePay(HttpServletRequest req, HttpServletResponse resp,Model model) {
		try {
			
			//商户订单号，商户网站订单系统中唯一订单号，必填
			String coNum = new String(req.getParameter("coNum").getBytes("ISO-8859-1"),"UTF-8");
			 //付款金额，必填
	        String txnAmt = new String(req.getParameter("txnAmt").getBytes("ISO-8859-1"),"UTF-8");
	        ConfigAlipay configAlipay = configAlipayService.getConfigAlipay();
	        
	        ShopOrder order = shopOrderService.findByCoNum(coNum);
			List<ShopOrderInfo> infos = order.getShopOrderInfoList();
			StringBuilder sbBody = new StringBuilder();
			for (ShopOrderInfo info : infos) {
				sbBody.append(info.getName()).append(",");
			}
	        model.addAttribute("coNum",coNum);
	        model.addAttribute("txnAmt",txnAmt);
	        model.addAttribute("body",sbBody.toString().substring(0, sbBody.toString().length() - 1));
	        model.addAttribute("subject",sbBody.toString().substring(0, sbBody.toString().length() - 1));
	        model.addAttribute("configAlipay",configAlipay);
	        
	        
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "modules/pay/ali/mobile/alipayapi";
	}
	
	
	@RequestMapping(value = "forResult")
	public void forResult(HttpServletRequest request, HttpServletResponse resp, Model model) {
		try {
			if (log.isDebugEnabled()) {
				log.debug("Enter method forResult()..");
			}
			//获取支付宝POST过来反馈信息
			Map requestParams = request.getParameterMap();
			aliPayService.forResult(requestParams, request);
		} catch (Exception e){
			e.printStackTrace();
		}
	}
	
	@RequestMapping(value = "forReturn")
	public String forReturn(HttpServletRequest request, HttpServletResponse resp,HttpSession session, Model model) {
		try {
			if (log.isDebugEnabled()) {
				log.debug("Enter method forReturn()..");
			}
			//获取支付宝POST过来反馈信息
			Map requestParams = request.getParameterMap();
			Map<String,String> resultMap = aliPayService.forReturn(requestParams, request);
			model.addAttribute("resultMap",resultMap);
		} catch (Exception e){
			e.printStackTrace();
		}
		
		return "modules/pay/ali/pay_result";
	}
	@RequestMapping(value = "forCheck")
	@ResponseBody
	public Object forCheck(HttpServletRequest req,String orderId, HttpServletResponse resp, Model model) {
		
		ConfigAlipay configAlipay = configAlipayService.getConfigAlipay();
		Map<String,Boolean> resultMap = new HashMap<String,Boolean>();
		EcPayLog log = new EcPayLog();
        log.setOrgCode(configAlipay.getSellerId());
        log.setMerChantid(configAlipay.getSellerId());
        log.setCoNum(orderId);
        // 根据订单号跟商户号  获取支付日志
		EcPayLog ecPayLog = ecPayLogService.getEcPayLogByCoNumOrgCode(log);
		if (ecPayLog != null) {// 有支付日志
        	//1.支付成功 0,支付失败2，结果不确定
        	if ("1".equals(ecPayLog.getPayFlag())) {
        		resultMap.put("canPay", false);
        	} else if ("0".equals(ecPayLog.getPayFlag())) {
        		resultMap.put("canPay", true);
        	} else if ("2".equals(ecPayLog.getPayFlag())) {
        		//TODO
        	}
        } else {// 没有支付日志，则从来没有支付过
        	resultMap.put("canPay", true);
        }
        return resultMap;
	}
	
}